package exam.test19;

public class Zero {

    public int zeroEdges(Node s) {
        int count = 0;
        s.mark();
        for (Edge edge : s.getIncidentEdges()) {
            if (edge.getLabel() != 0 || edge.isMarked()) {
                continue;
            }
            edge.mark();

            count++;
            Node nextNode = edge.firstEndpoint();
            if (edge.firstEndpoint().equals(s)) {
                nextNode = edge.secondEndpoint();
            }

            if (!nextNode.marked) {
                count += zeroEdges(nextNode);
            }
        }

        return count;
    }

    public static void main(String[] args) {
        int[][] graph = {{1, 3}, {0, 2, 3, 8}, {1, 3, 4, 5}, {0, 1, 2, 7}, {2, 5, 6, 8}, {2, 4, 7}, {4, 7, 8}, {3, 5, 6}, {1, 4, 6}};
        int[][] edgeLabels = {{0, 0}, {0, 1, 0, 1}, {1, 0, 1, 0}, {0, 0, 0, 0}, {1, 0, 0, -1}, {0, 0, -1}, {0, 1, -1}, {0, -1, 1}, {1, -1, 1}};

        Node[] V = buildGraph(graph, edgeLabels, null);

        Zero program = new Zero();
        int result = program.zeroEdges(V[0]);
        System.out.println(result);


    }

    private static Node[] buildGraph(int[][] graph, int[][] edgeLabels, int[] nodeLabels) {
        Node[] V = new Node[graph.length];
        Node[] listNodes;
        Edge[] listEdges;

        for (int i = 0; i < graph.length; i++) {
            if (nodeLabels != null) {
                V[i] = new Node(nodeLabels[i], i);
            } else {
                V[i] = new Node(i);
            }
        }

        for (int i = 0; i < graph.length; i++) {
            listNodes = new Node[graph[i].length];
            listEdges = new Edge[graph[i].length];
            for (int j = 0; j < graph[i].length; j++) {
                listNodes[j] = V[graph[i][j]];
                listEdges[j] = addEdge(i, graph[i][j], edgeLabels[i][j], V);
            }
        }
        return new Node[0];
    }

    private static Edge addEdge(int u, int v, int label, Node[] V) {
        Edge[] listEdges;
        Edge e;
        if (v < u) {
            listEdges = V[v].getIncidentEdges();
            for (int i = 0; i < listEdges.length; i++) {
                if (listEdges[i].secondEndpoint() == V[u]) {
                    e = new Edge(label, V[u], V[v]);
                    e.setTwin(listEdges[i]);
                    listEdges[i].setTwin(e);
                    return e;
                }
            }
        }
        return new Edge(label, V[u], V[v]);
    }
}
